package server;

import java.io.*;

public class MyClassLoader extends ClassLoader {

    private String rootPath;

    public MyClassLoader(String rootPath) {
        this.rootPath = rootPath;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        Class<?> loadedClass = findLoadedClass(name);
        if (loadedClass != null) {
            return loadedClass;
        }

        byte[] classData = getClassData(name);
        if(classData == null) {
            throw new ClassNotFoundException();
        }

        return defineClass(name, classData, 0, classData.length);
    }

    private byte[] getClassData(String name) {
        //类的绝对路径
        String classFileName = "";
        FileInputStream fileInputStream = null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        byte[] buffer = new byte[1024];
        int length = 0;

        // 根据给定的类的全限定名称计算类的绝对路径
        if (name != null && name != "") {
            classFileName = rootPath + "/" + name.replace(".", "/") + ".class";
        }

        // 将类从文件中读取并写入到字节数组中
        try {
            fileInputStream = new FileInputStream(new File(classFileName));
            byteArrayOutputStream = new ByteArrayOutputStream();
            while ((length = fileInputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, length);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                byteArrayOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return byteArrayOutputStream.toByteArray();
    }
}
